package com.key.w8.http1.connection.client;

import com.key.w8.http1.connection.connectionImpl.ClientHttp1PersistentConnection;
import com.key.w8.http1.connection.pool.ClientConnectionBuilder;

import java.util.concurrent.*;

/**
 * @Author: k8
 * @CreateTime: 2025-04-24
 * @Version: 1.0
 */
public class ShortConnectionClient {
    private ClientConnectionBuilder builder;
    private long timeOut;
    private TimeUnit timeUnit;
    private ExecutorService executorService;

    public ShortConnectionClient(ClientConnectionBuilder builder, long timeOut, TimeUnit timeUnit) {
        this.builder = builder;
        this.timeOut = timeOut;
        this.timeUnit = timeUnit;
    }
    public ShortConnection createShortConnection(String host, int port) throws ExecutionException, InterruptedException, TimeoutException {
        FutureTask<Void> futureTask = new FutureTask<>(()->{
            return null;
        });
        builder.addCreatedListener((connection)->{
            futureTask.run();
        });
        ClientHttp1PersistentConnection connection = builder.build(host,port);
        //等待channelActive执行准备好了一些东西才算连接成功
        futureTask.get(timeOut,timeUnit);
        return new ShortConnection(executorService,connection);
    }
    public ShortConnection createShortConnection() throws ExecutionException, InterruptedException, TimeoutException {
        FutureTask<Void> futureTask = new FutureTask<>(()->{
            return null;
        });
        builder.addCreatedListener((connection)->{
            futureTask.run();
        });
        ClientHttp1PersistentConnection connection = builder.build();
        //等待channelActive执行准备好了一些东西才算连接成功
        futureTask.get(timeOut,timeUnit);
        return new ShortConnection(executorService,connection);
    }

    public void setExecutorService(ExecutorService executorService) {
        this.executorService = executorService;
    }
}
